package B刷题.A栈和队列;

import java.util.Stack;

/**
 * @author wei.zhao
 * @description: 20.有效的括号
 * @date 2022年04月10日 20:38
 */
public class Code01_IsValidParentheses {

    /**
     * 遍历所有的字符；
     * 遇到左括号，入栈；
     * 遇到右括号，栈为空肯定无效，栈不为空弹出栈顶的左括号，不匹配肯定无效；
     * 遍历结束，判断栈是否为空，不为空则无效。
     */
    public static final char minLeft = '(';
    public static final char midLeft = '[';
    public static final char maxLeft = '{';
    public static final char minRight = ')';
    public static final char midRight = ']';
    public static final char maxRight = '}';

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == minLeft || c == midLeft || c == maxLeft) {
                stack.add(c);
            } else {
                if (stack.isEmpty()) {
                    return false;
                } else {
                    Character pop = stack.pop();
                    if (!isPair(pop, c)) {
                        return false;
                    }
                }
            }
        }
        return stack.isEmpty();
    }

    private boolean isPair(char left, char right) {
        Character pair = null;
        switch (left) {
            case minLeft:
                pair = minRight;
                break;
            case midLeft:
                pair = midRight;
                break;
            case maxLeft:
                pair = maxRight;
                break;
        }
        return pair == right;
    }

}
